#!/usr/bin/env python3
"""
测试超时修复和调试信息
"""

import requests
import json
import time

def test_ai_analysis_timeout():
    """测试AI分析超时修复"""
    print("[SEARCH] 测试AI分析超时修复...")
    
    # 检查是否有日志数据
    try:
        response = requests.get("http://localhost:8080/analysis", timeout=5)
        if response.status_code != 200:
            print("[WARN]  没有日志数据，请先上传日志文件")
            return False
    except Exception as e:
        print(f"[FAIL] 无法连接到服务器: {e}")
        return False
    
    # 测试AI分析（应该不会超时）
    try:
        print("[WAIT] 开始AI分析，等待响应...")
        start_time = time.time()
        
        response = requests.post(
            "http://localhost:8080/ai/analyze", 
            timeout=150,  # 2.5分钟超时
            json={}
        )
        
        end_time = time.time()
        duration = end_time - start_time
        
        print(f"⏱️  分析耗时: {duration:.2f} 秒")
        
        if response.status_code == 200:
            result = response.json()
            if 'initial_analysis' in result:
                print("[PASS] AI分析成功完成")
                print(f"   分析内容长度: {len(result['initial_analysis'])} 字符")
                return True
            else:
                print("[WARN]  AI分析返回结果异常")
                return False
        else:
            print(f"[FAIL] AI分析请求失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except requests.Timeout:
        print("[FAIL] AI分析超时（超过2.5分钟）")
        return False
    except Exception as e:
        print(f"[FAIL] AI分析测试失败: {e}")
        return False

def test_ai_question_timeout():
    """测试AI问答超时修复"""
    print("\n[SEARCH] 测试AI问答超时修复...")
    
    try:
        print("[WAIT] 发送AI问题，等待响应...")
        start_time = time.time()
        
        response = requests.post(
            "http://localhost:8080/ai/ask",
            timeout=150,  # 2.5分钟超时
            json={"question": "请简单分析一下这些日志中的主要问题"}
        )
        
        end_time = time.time()
        duration = end_time - start_time
        
        print(f"⏱️  问答耗时: {duration:.2f} 秒")
        
        if response.status_code == 200:
            result = response.json()
            if 'answer' in result:
                print("[PASS] AI问答成功完成")
                print(f"   回答长度: {len(result['answer'])} 字符")
                return True
            else:
                print("[WARN]  AI问答返回结果异常")
                return False
        else:
            print(f"[FAIL] AI问答请求失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except requests.Timeout:
        print("[FAIL] AI问答超时（超过2.5分钟）")
        return False
    except Exception as e:
        print(f"[FAIL] AI问答测试失败: {e}")
        return False

def main():
    """主函数"""
    print("[START] 开始测试超时修复...")
    print("=" * 50)
    
    # 测试AI分析
    analysis_success = test_ai_analysis_timeout()
    
    # 测试AI问答
    question_success = test_ai_question_timeout()
    
    print("\n" + "=" * 50)
    print("[STATS] 测试结果汇总:")
    print(f"   AI分析: {'[PASS] 通过' if analysis_success else '[FAIL] 失败'}")
    print(f"   AI问答: {'[PASS] 通过' if question_success else '[FAIL] 失败'}")
    
    if analysis_success and question_success:
        print("\n[SUCCESS] 所有测试通过！超时修复成功。")
        print("[TIP] 现在可以查看后端日志来调试AI调用过程。")
    else:
        print("\n[WARN]  部分测试失败，请检查后端日志获取详细信息。")

if __name__ == "__main__":
    main() 